const router = require("koa-router")();
const User = require("../models/usersSchema");
const utils = require("../utils/utils");
var jwt = require("jsonwebtoken");
const Counter = require("../models/counterSchema");
const { success, fail } = require("../utils/utils");
router.prefix("/users");
// 登录接口
router.post("/login", async (ctx, next) => {
  const { userName, password } = ctx.request.body;
  let res = await User.findOne(
    {
      userName,
      password,
    },
    "userId userName userEmail state role deptId roleList"
  );
  if (res) {
    let data = res._doc;
    let token = jwt.sign(
      {
        data,
      },
      "yao",
      { expiresIn: "48h" }
    );
    data.token = token;
    ctx.body = utils.success({ data: res });
  }
});

// 请求表单数据
router.get("/list", async (ctx, next) => {
  const { userId, userName, state } = ctx.request.query;
  const { page, skipIndex } = utils.pager(ctx.request.query);
  let params = {};
  if (userId) params.userId = userId;
  if (userName) params.userName = userName;
  if (state && state != 0) params.state = state;
  try {
    let query = User.find(params, { _id: 0, userPwd: 0 });
    let [list, total] = await Promise.all([
      query.skip(skipIndex).limit(page.pageNum),
      User.countDocuments(params),
    ]);
    ctx.body = utils.success({
      data: {
        page: {
          total,
          list,
        },
      },
    });
  } catch (error) {
    console.log(error);
  }
});

// 删除表单
router.post("/delete", async (ctx, next) => {
  const { userIds } = ctx.request.body;
  console.log(userIds);
  if (userIds == undefined) {
    ctx.body = fail({ data: null, msg: "修改失败,参数填写错误", code: 400 });
    return;
  }
  // 比较运算符
  try {
    const res = await User.updateMany(
      { userId: { $in: userIds } },
      { state: 2 }
    );
    ctx.body = success({ data: null, msg: "修改成功", code: 200 });
  } catch (error) {
    ctx.body = fail({ data: null, msg: "修改失败" });
  }
});

// 编辑表单用户信息
router.post("/edit", async (ctx, next) => {
  const {
    userId,
    userName,
    userEmail,
    mobile,
    job,
    state,
    roleList,
    deptId,
    type,
  } = ctx.request.body;
  if (!userName) {
    ctx.body = utils.fail({ data: null, msg: "请填写用户名", code: 400 });
  } else if (!userEmail) {
    ctx.body = utils.fail({ data: null, msg: "请填写用户邮箱", code: 400 });
  } else if (!deptId) {
    ctx.body = utils.fail({ data: null, msg: "请填写相关部门", code: 400 });
  } else {
    // 查询有没有重复信息
    let res = await User.findOne(
      { $or: [{ userName }, { userEmail }] },
      "_id userName userEmail"
    );
    if (res) {
      ctx.body = utils.fail({
        data: null,
        msg: `检测到有重复用户,请勿重复添加`,
        code: 400,
      });
    }
    console.log(type);
    if (type == "Add") {
      let doc = await Counter.findOneAndUpdate(
        { _id: "userId" },
        { $inc: { sequence_value: 1 } },
        { new: true }
      );
      console.log(doc);
      let user = new User({
        userId: doc.sequence_value,
        userName,
        userPwd: "123456",
        userEmail,
        mobile,
        job,
        state,
        roleList,
        deptId,
      });
      user.save();
      ctx.body = utils.success({ data: null, mag: "用户添加成功", code: 200 });
    } else if (type == "Edit") {
      try {
        let res = await User.findOneAndUpdate(
          { userId },
          { userName, userEmail, mobile, job, state, roleList, deptId }
        );
        ctx.body = utils.success({ data: null, msg: "编辑成功", code: 200 });
      } catch (error) {
        ctx.body = utils.fail({ data: null, msg: "编辑失败" });
      }
    }
  }
});

module.exports = router;
